package amu.action;

import java.util.List;

import amu.database.BookDAO;
import amu.database.ReviewDAO;
import amu.model.Book;
import amu.model.Customer;
import amu.model.Review;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PostReviewAction implements Action {

	@Override
	public ActionResponse execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		HttpSession session = request.getSession(true);
        Customer customer = (Customer) session.getAttribute("customer");
        
        if (customer == null) {
            ActionResponse actionResponse = new ActionResponse(ActionResponseType.REDIRECT, "loginCustomer");
            actionResponse.addParameter("from", "viewBook");
            return actionResponse;
        }
        
        if (request.getMethod().equals("POST")) {
            int id = Integer.parseInt(request.getParameter("id"));
            int rating = Integer.parseInt(request.getParameter("rating"));
            String review = request.getParameter("review");
            BookDAO bookDAO = new BookDAO();
            Book book = bookDAO.findByID(id);
            ReviewDAO reviewDAO = new ReviewDAO();
            Review reviewObject = new Review(customer, review, book, rating);
            if (reviewDAO.add(reviewObject)) {
            	ActionResponse actionResponse = new ActionResponse(ActionResponseType.REDIRECT, "viewBook");
            	actionResponse.addParameter("isbn", book.getIsbn13());
                return actionResponse;                
            }        	
        }        
		return new ActionResponse(ActionResponseType.REDIRECT, "viewBook");
	}

}
